#pragma once
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

const std::string gpipe_file = "./fifo"; // 命名管道的路径
const mode_t gfifo_mode = 0600;          // 命名管道的权限
const int gfifo_size = 1024;
const int gdefaultfd = -1;
const int OpenForRead = O_RDONLY;
const int OpenForWrite = O_WRONLY;

class Fifo
{
private:
    // 打开管道
    void OpenFifo(int flag)
    {
        _fd = ::open(gpipe_file.c_str(), flag);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
        }
    }

public:
    Fifo() : _fd(gdefaultfd)
    {
        umask(0);
        // 创建管道
        int n = mkfifo(gpipe_file.c_str(), gfifo_mode);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        std::cout << "mkfifo success" << std::endl;
    }

    // 为了读打开管道
    bool OpenPipeForRead()
    {
        OpenFifo(OpenForRead);
        if (_fd < 0)
            return false;
        return true;
    }
    // 为了写打开管道
    bool OpenPipeForWrite()
    {
        OpenFifo(OpenForWrite);
        if (_fd < 0)
            return false;
        return true;
    }

    int Wait()
    {
        // std::cout << "pos 1" << std::endl;
        int code = 0;
        ssize_t n = ::read(_fd, &code, sizeof(code));
        // std::cout << "n = " << n << std::endl;
        if (n == sizeof(code))
        {
            // std::cout << "pos 2" << std::endl;
            return 0; // 读到写入的数据就相当于唤醒该进程去访问共享内存
        }
        else if (n == 0)
        {
            // std::cout << "pos 3" << std::endl;
            return 1; // 返回0标识读到文件末尾，即写端关闭，读端也关闭
        }
        else
        {
            // std::cout << "pos 4" << std::endl;
            return 2;
        }
    }

    void Signal()
    {
        int code = 1;
        ::write(_fd, &code, sizeof(code));
    }

    ~Fifo()
    {
        // 关闭管道
        if (_fd >= 0)
            ::close(_fd);
        // 删除管道
        int n = unlink(gpipe_file.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }

private:
    int _fd;
};

Fifo gfifo;